package com.molichuxing.gateway.bff.order.services.impl;

import com.molichuxing.framework.dto.Paged;
import com.molichuxing.framework.dto.TabDto;
import com.molichuxing.framework.exception.BizException;
import com.molichuxing.framework.utils.ObjectCastUtil;
import com.molichuxing.gateway.bff.order.convertor.Convert;
import com.molichuxing.gateway.bff.order.entity.request.create.OrderLawsuitCreateVo;
import com.molichuxing.gateway.bff.order.entity.request.modify.OrderLawsuitModifyVo;
import com.molichuxing.gateway.bff.order.entity.response.OrderLawsuitVo;
import com.molichuxing.gateway.bff.order.services.OrderLawsuitBffService;
import com.molichuxing.services.business.service.LawsuitBizService;
import com.molichuxing.services.infrastructure.dto.response.LawsuitListDto;
import com.molichuxing.services.infrastructure.dto.response.UserDto;
import com.molichuxing.services.infrastructure.service.*;
import com.molichuxing.services.property.OrderRenegeTypeEnum;
import com.molichuxing.services.property.OrderTypeEnum;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @Author zoumingyu
 * @Date 2020年07月20日
 */
@Service("orderLawsuitBffService")
public class OrderLawsuitBffServiceImpl implements OrderLawsuitBffService {
    private static final Logger logger = LoggerFactory.getLogger(OrderLawsuitBffServiceImpl.class);

    @Resource
    private LawsuitBizService lawsuitBizService;

    @Resource
    private LawsuitService lawsuitService;

    @Resource
    private OrderScheduleService orderScheduleService;

    @Resource
    private OrderRenegeService orderRenegeService;

    @Resource
    private RecycleCarsService recycleCarsService;

    @Resource
    private UserService userService;

    /**
     * 查询法务诉讼列表
     *
     * @param selectParams
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Override
    public Paged<OrderLawsuitVo> getLawsuitList(Map<String, Object> params,
                                                Integer pageNum, Integer pageSize) throws Exception {
        Paged<OrderLawsuitVo> result = new Paged<>(new ArrayList<>(), 0, pageSize);
        // 查询tab页签数量
        result.setTab(getOverdueTab());
        // 判断查询条件是否有用户信息
        if (StringUtils.isNotBlank(ObjectCastUtil.castString(params.get("userRealName")))
                || StringUtils.isNotBlank(ObjectCastUtil.castString(params.get("userPhone")))) {
            // 查询用户ids
            List<Integer> userIdList = getUserIds(ObjectCastUtil.castString(params.get("userRealName")),
                    ObjectCastUtil.castString(params.get("userPhone")));
            if (userIdList == null || userIdList.size() <= 0) {
                // 用户不存在
                return result;
            }
            params.put("userIds", userIdList);
            params.remove("userRealName");
            params.remove("userPhone");
            logger.info("[getLawsuitList]分页获取法务诉讼列表userIds：" + userIdList);
        }
        // 查询收车记录表数量
//        int recycleCount = recycleCarsService.getRecycleCarsTotal();
//        params.put("recycleCount", recycleCount);

        Paged<LawsuitListDto> LawsuitListDtos = lawsuitService.getPaged(params, pageNum, pageSize);
        // 判断是否查询为空
        if (LawsuitListDtos == null) {
            return result;
        } else if (LawsuitListDtos.isEmpty()) {
            return result.setTotal(LawsuitListDtos.getTotal());
        }

        result.setTotal(LawsuitListDtos.getTotal());
        // 用户id集合
        List<Integer> userIds = new ArrayList<>();
        for (LawsuitListDto lawsuitListDto : LawsuitListDtos
                .getList()) {
            userIds.add(lawsuitListDto.getUserId());
            result.getList().add(Convert.toOrderLawsuitVo(lawsuitListDto));
        }
        // 查询用户
        Map<Integer, UserDto> userMap = userService.getUsers(userIds);

        for (OrderLawsuitVo vo : result.getList()) {
            // 用户
            UserDto userDto = userMap == null ? null
                    : userMap.isEmpty() ? null : userMap.get(vo.getUserId());
            // 用户手机号
            vo.setUserPhone(userDto == null ? null : userDto.getPhone());
            // 用户姓名
            vo.setUserName(userDto == null ? null : userDto.getRealName());
        }

        return result;
    }

    private List<TabDto> getOverdueTab() throws Exception {
        List<TabDto> tabs = new ArrayList<>();
        // 逾期未还数量
        tabs.add(new TabDto("逾期未还款", 1,
                orderScheduleService.getOverdueTotal(OrderTypeEnum.EXCLUSIVEL)));
        // 协商退租数量
        tabs.add(new TabDto("逾期协商退租", 2,
                orderRenegeService.getRenegeTotal(OrderRenegeTypeEnum.NEGOTIATE)));
        // 法务诉讼数量
        tabs.add(new TabDto("法务诉讼", 3, lawsuitService.getLawsuitTotal()));
        return tabs;
    }

    /**
     * 根据用户姓名和手机号查询用户ids
     *
     * @param userRealName 用户姓名
     * @param userPhone    用户手机号
     * @return
     */
    private List<Integer> getUserIds(String userRealName, String userPhone) {
        List<Integer> result = null;
        // 查询用信息
        List<UserDto> userDtoList = userService.getUserList(null, userRealName, userPhone);
        if (userDtoList == null || userDtoList.isEmpty()) {
            // 用户不存在
            return result;
        }
        result = new ArrayList<>();
        for (UserDto userDto : userDtoList) {
            result.add(userDto.getId());
        }

        return result;
    }

    /**
     * 法务诉讼
     *
     * @param createVo 新增参数
     * @return Boolean
     */
    @Override
    public Boolean createLawsuit(OrderLawsuitCreateVo createVo) {
        return lawsuitBizService.create(Convert.toLawsuitCreateBizDto(createVo));
    }

    /**
     * 完成诉讼
     *
     * @param modifyVo 修改参数
     * @return Boolean
     */
    @Override
    public Boolean modifyLawsuitComplete(OrderLawsuitModifyVo modifyVo) throws BizException {
        return lawsuitBizService.modifyLawsuitComplete(modifyVo.getOrderCode());
    }
}
